/*
 * @FileDescription: axios封装
 * @Author: zsf
 * @Date: 2021-07-02 09:47:28
 * @LastEditors: zsf
 * @LastEditTime: 2021-07-15 10:54:07
 */
import axios from 'axios'
import Cookies from 'js-cookie'
import { message } from 'antd'
import baseURL from '../../baseURL.js'
import history from '@/router/history.js';

/**
 * 请求拦截器
 */
axios.interceptors.request.use(function (config) { 
  let cookiesTemp = Cookies.get('token');
  if (cookiesTemp) {
    // 让每个请求携带token
    config.headers['token'] = cookiesTemp
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

/**
 * 响应拦截器
 */
axios.interceptors.response.use((response) => {
  // 判断响应结果
  let res = response.data;

    if (+res.code === 444) {
    Cookies.remove('token')
    history.push('/Login');
  } else if (+res.code === 307) {
    // router.replace('/updataing');
    return response;
  } else if (+res.code === 200) {
    if (response.config.extraOptions && response.config.extraOptions.showTips) {
      message.success(res.msg || "操作成功!")
    }
    return response;
  } else if ([400, 402, 500, 404].includes(+res.code)) {
    if (response.config.extraOptions && response.config.extraOptions.showTips) {
      message.error(res.msg)
    }
    return response;
  } else {
    return response;
  }
}, (error) => {
  message.error(error)
  return Promise.reject(error);
});

axios.defaults.baseURL = baseURL;

// 二次封装HTTP REQUEST METHODS
/**
 * GET
 * @param {*} url 
 * @param {*} params 
 * @param {object} extraOptions 额外自定义配置项 请求拦截器中使用
 * @returns 
 */
export const GET = (url, params, extraOptions) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "GET",
      url,
      params,
      extraOptions,
    }).then(res => {
      resolve(res);
    });
  });
}

/**
 * POST
 * @param {*} url 
 * @param {*} data 
 * @param {object} extraOptions 额外自定义配置项 请求拦截器中使用
 * @returns 
 */
export const POST = (url, data, extraOptions) => {
  // 合并配置项
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url,
      data,
      extraOptions,
    }).then(res => {
      resolve(res);
    });
  });
}

export default axios